/*
 * @Author: CPS
 * @Date: 2020-07-10 22:13:34
 * @Last Modified by: CPS
 * @Last Modified time: 2020-08-31 22:32:17
 * @Projectname Electron-YYS
 * @Filename fileWatcher.js
 */

'use strict'
// 监听文件模块
import watch from '@api/watcher'

// 弹出通知模块
import notification from './notification'

// 文件列表页面
import fileListPage from './fileList'

// 配置页面
import configPage from './config'

//载入路由
import Router from '@api/router'

export default (fwData) => {
  if (global.fw) return global.fw //不重复创建本对象

  return {
    '通知栏': notification(cps.$('#' + fwData['fileWatcher']['通知栏']['id'])),

    // 内部属性
    selPath: '', //保存已关联的文件夹,以后修改成数组
    fileObecjt: {},

    // 页面实例
    fileListPage: new fileListPage(),
    configPage: new configPage(),

    watchList: [],
    watching: 0, // 表示当前是否已启动监听功能

    init: () => {

    },

    showPage: (page, data) => {
      switch (page) {
        case 'config':
          fw['configPage'].show()
          break;

        case 'notify':
          fw['notifypage'].show(data)

          break;
        default:
          // statements_def
          break;
      }
    },

    /**
     * 遍历目录进行html元素的创建
     *
     * @param      {<type>}  tarPaths  The tar paths
     * @return     {<type>}  { description_of_the_return_value }
     */
    addFolder: (tarPaths) => {
      if (!tarPaths) return console.log('tarPath是空的')
      fw['fileListPage'].createContent(tarPaths)
    },

    /**
     * 添加文件夹到视图
     * @param      {<type>}  tarPath  The tar path
     * @return     {<type>}  { description_of_the_return_value }
     */
    pushFolder: (tarPath, position = 'before') => {
      if (!tarPath) return console.log('输入的目录不合法')
      fw['fileListPage'].pushFolder(tarPath)
    },

    // 创建下方推送通知
    addNotice: (msg) => {
      //添加开关控制
      let sendSubWindow
      let sendNotices

      //判断是否需要发送推送和弹窗
      if (!YYS.win.isVisible() || YYS.win.isMinimized()) {
        console.log('最小化监测到变动')
        //当前窗口不可见
        if (fw['config']['subWindow'] == 'auto') {
          sendSubWindow = true
        }
      } else {
        //当前窗口可见
        sendNotices = true
      }

      //发送弹窗
      if (sendSubWindow) {
        //创建弹窗进程
        YYS.sendMain('create-subWindow', {
          x: YYS.width - 320,
          y: YYS.height - 370,
          width: 320,
          height: 340,
        })

        //创建弹窗消息
        YYS.sendMain('new-msg', msg)
      }

      //创建推送通知
      if (sendNotices) {
        if (!fw['通知栏']) {
          fw['通知栏'] = notification(cps.$('#' + fwData['fileWatcher']['通知栏']['id']))
        }

        // 推送消息
        fw['通知栏'].pushMsg({
          icon: fwData.icon, //传入icon对象,需要定制
          msg: {
            content: msg ? msg : '新消息!!!',
            delay: 5000
          }
        })
      }
    },

    //监视文件夹变化
    watchFolder: (tarPath) => {
      let dirName = path.basename(tarPath)
      let watcher = watch(tarPath, {
        addDir: fw.whenDirAdd, //对应事件添加监听器
        add: fw.whenFileAdd, //对应事件添加监听器
        error: fw.whenError //对应事件添加监听器
      })

      if (fw['watching']) return console.log('当前已经在监听')

      setTimeout(() => { //延时开启(因为首次创建监听,也会触发一堆事件)
        fw['watching'] = 1
      }, 3000)

      // 创建一个监听列表,用户批量管理
      fw['watchList'].push(watcher)
    },

    whenFileAdd: (p) => { //发生文件添加时
      if (!fw['watching']) return
      let currtPath = path.dirname(path.resolve(p))
      let watchPath = path.resolve(fw['selPath'])

      if (currtPath == watchPath) {
        log('主目录发生创建文件事件', )
        // console.log('发生创建的文件 [', path.basename(p), ']')
      } else {
        log('子目录发生创建文件事件')
        // console.log('子目录:' + path.basename(path.dirname(p)))
        // console.log('新文件:' + path.basename(p))
      }
    },

    whenDirAdd: (p) => { //发生文件夹添加时
      if (!fw['watching']) return
      //先判断返回的p的合法性
      let tarPath = path.resolve(p)
      let currtPath = path.dirname(tarPath)
      let watchPath = path.resolve(fw['selPath'])

      //判断是否主目录发生了变化
      if (currtPath == watchPath) {
        log('主目录发生创建事件', path.basename(p))

        //创建推送通知
        fw.addNotice('+ 文件夹创建[' + path.basename(p) + ']')

        setTimeout(() => {
          fw.pushFolder(tarPath)
        }, 300, tarPath)

        // 自动打开功能
        // 判断是否开启了自动打开功能

      } else {
        log('子目录创建目录事件:', watchPath)
      }
    },

    whenError: () => {

    },

    close: () => {
      if (fw['watchList'].length > 0) {
        fw['watchList'].forEach(item => {
          console.log('关闭一个监听,')
          item.close()
        })
      }
      fw['watching'] = 0
      fw['selPath'] = ''
      fw['folderList'] = []
    },

    clean: () => {
      fw['fileListPage'].clean()
    }
  }
}
